package main

import (
	"fmt"
	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	"net/http"
	"os"
	"time"
)

var router *gin.Engine

func init() {
	// 设置全局时区为上海
	loc, err := time.LoadLocation("Asia/Shanghai")
	if err != nil {
		panic(err)
	}
	time.Local = loc // 关键！设置全局本地时区

	// 加载配置
	err = LoadConfig("config.json")
	if err != nil {
		fmt.Println("加载配置失败")
		panic(err)
	}

	// 初始化Redis连接
	if err := initRedis(); err != nil {
		fmt.Println("初始化Redis连接失败")
		panic(err)
	}

	// 初始化路由
	router = setupRouter()
}

func setupRouter() *gin.Engine {
	gin.SetMode(gin.ReleaseMode)

	r := gin.Default()

	// 添加 CORS 中间件
	r.Use(cors.New(cors.Config{
		AllowOrigins:     []string{"*"},                                                 // 允许所有来源
		AllowMethods:     []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},           // 允许的请求方法
		AllowHeaders:     []string{"Origin", "Content-Type", "Accept", "Authorization"}, // 允许的请求头
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: true,
		MaxAge:           12 * 60 * 60, // 预检请求结果缓存时间（秒）
	}))

	// 健康检查
	r.GET("/health", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"status":    "ok",
			"timestamp": time.Now().Format(time.RFC3339),
			"environment": map[string]string{
				"function_name":    os.Getenv("FC_FUNCTION_NAME"),
				"function_handler": os.Getenv("FC_FUNCTION_HANDLER"),
			},
		})
	})

	// 配置信息
	r.GET("/config", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "success",
			"data": GlobalConfig,
		})
	})
	r.POST("/retry", handleRetryFailedMessages)

	msg := r.Group("msg")
	{
		msg.POST("/:queueName", handlePostMessage)
		msg.GET("/:queueName", handleGetMessage)
	}

	msg2 := r.Group("msg2")
	{
		msg2.POST("/:queueName", handlePostMessage2)
		msg2.GET("/:queueName", handleGetMessage2)
	}

	// 巨量spi
	oceanSpi := r.Group("ocean_spi")
	{
		oceanSpi.GET("", handleOceanSpiMessage)
		oceanSpi.POST("", handleOceanSpiMessage)
	}

	return r
}

func main() {
	router.Run(":80")
}
